<!--
 * @Author: ZAL 2177624751@qq.com
 * @Date: 2025-03-30 16:43:41
 * @LastEditors: ZAL 2177624751@qq.com
 * @LastEditTime: 2025-03-31 15:06:38
 * @FilePath: \shop_app_vue3\pages\user\components\addAddress.vue
 * @Description: 添加/编辑地址页面
-->
<template>
  <view class="address-container">
    <view class="form-group">
      <u-cell-group>
        <u-cell title="收货人">
          <template #value>
            <u-input 
              v-model="addressForm.receiverName"
              placeholder="请输入收货人姓名"
              :border="false"
              class="input-field"
            ></u-input>
          </template>
        </u-cell>
        <u-cell title="手机号码">
          <template #value>
            <u-input 
              v-model="addressForm.receiverPhone"
              placeholder="请输入手机号码"
              :maxlength="11"
              :border="false"
              class="input-field"
            ></u-input>
          </template>
        </u-cell>
        <pick-regions
          :defaultRegion="[addressForm.province, addressForm.city, addressForm.district]"
          @getRegion="handleRegionSelect"
        >
          <u-cell 
            title="所在地区" 
            center 
            :isLink="true" 
            :value="regionText"
          ></u-cell>
        </pick-regions>
        <u-cell title="详细地址">
          <template #value>
            <u-input 
              v-model="addressForm.detailAddress"
              type="textarea"
              placeholder="请输入详细地址信息，如街道、楼牌号等"
              :border="false"
              class="input-field textarea"
            ></u-input>
          </template>
        </u-cell>
      </u-cell-group>

      <view class="default-address">
        <u-cell title="设为默认地址">
          <template #value>
            <u-switch 
              v-model="isDefaultSwitch"
              :active-value="1"
              :inactive-value="0"
              activeColor="#00b578"
              size="28"
              @change="onDefaultChange"
            ></u-switch>
          </template>
        </u-cell>
      </view>

      <view class="tips">
        <text class="tip-content">· 请确保收货信息准确无误，以免影响收货</text>
        <text class="tip-content">· 设为默认地址后，下次下单会优先使用该地址</text>
      </view>
    </view>

    <view class="footer">
      <u-button 
        type="primary" 
        color="#00b578"
        @click="handleSubmit"
        :loading="loading"
      >保存地址</u-button>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useAddressStore } from '@/store/addressStore'
import PickRegions from '@/components/pick-regions/pick-regions.vue'
import { onLoad } from '@dcloudio/uni-app'

const addressStore = useAddressStore()
const loading = ref(false)
const addressId = ref(null)
const isEdit = computed(() => !!addressId.value)

const addressForm = ref({
  id: null,
  receiverName: '',
  receiverPhone: '',
  province: '',
  city: '',
  district: '',
  detailAddress: '',
  isDefault: 0
})

const isDefaultSwitch = computed({
  get: () => addressForm.value.isDefault,
  set: (val) => {
    addressForm.value.isDefault = val
  }
})

const regionText = computed(() => {
  const { province, city, district } = addressForm.value
  if (!province && !city && !district) return '请选择所在地区'
  return `${province}${city}${district}`
})

const handleRegionSelect = (regions) => {
  addressForm.value.province = regions[0].name
  addressForm.value.city = regions[1].name
  addressForm.value.district = regions[2].name
}

const onDefaultChange = (value) => {
  addressForm.value.isDefault = value
}

const validateForm = () => {
  if (!addressForm.value.receiverName) {
    uni.showToast({ title: '请输入收货人姓名', icon: 'none' })
    return false
  }
  if (!addressForm.value.receiverPhone) {
    uni.showToast({ title: '请输入手机号码', icon: 'none' })
    return false
  }
  
  const phoneReg = /^1[3-9]\d{9}$/
  const phone = String(addressForm.value.receiverPhone).trim()
  if (!phoneReg.test(phone)) {
    uni.showToast({ title: '请输入正确的手机号码', icon: 'none' })
    return false
  }
  
  if (!addressForm.value.province || !addressForm.value.city || !addressForm.value.district) {
    uni.showToast({ title: '请选择所在地区', icon: 'none' })
    return false
  }
  if (!addressForm.value.detailAddress) {
    uni.showToast({ title: '请输入详细地址', icon: 'none' })
    return false
  }
  return true
}

const handleSubmit = async () => {
  if (!validateForm()) return
  
  loading.value = true
  try {
    const addressDTO = {
      ...addressForm.value
    }
    
    if (isEdit.value) {
      await addressStore.updateExistingAddress(addressDTO)
    } else {
      await addressStore.addNewAddress(addressDTO)
    }
    
    uni.showToast({
      title: '保存成功',
      icon: 'success'
    })
    
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
  } catch (error) {
    uni.showToast({
      title: '保存失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

onLoad((options) => {
  if (options) {
    addressId.value = options.id
    addressForm.value = {
      id: options.id,
      receiverName: options.receiverName || '',
      receiverPhone: String(options.receiverPhone || ''),
      province: decodeURIComponent(options.province || ''),
      city: decodeURIComponent(options.city || ''),
      district: decodeURIComponent(options.district || ''),
      detailAddress: options.detailAddress || '',
      isDefault: parseInt(options.isDefault || '0')
    }
  }
})
</script>

<style lang="scss" scoped>
.address-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: calc(env(safe-area-inset-bottom) + 120rpx);
}

.form-group {
  margin-top: 20rpx;
  
  .input-field {
    flex: 1;
    margin-left: 20rpx;
    
    &.textarea {
      height: 120rpx;
    }
  }
  
  :deep(.u-cell-group) {
    margin-bottom: 20rpx;
    background-color: #fff;
    
    .u-cell {
      min-height: 100rpx;
      padding: 24rpx 32rpx;
      
      &__title {
        font-size: 28rpx;
        color: #333;
        font-weight: normal;
      }
      
      &__value {
        color: #666;
        font-size: 28rpx;
      }
    }
  }
}

.default-address {
  background-color: #fff;
  margin-bottom: 20rpx;
}

.tips {
  padding: 32rpx;
  
  .tip-content {
    display: block;
    font-size: 24rpx;
    color: #999;
    line-height: 1.6;
    margin-bottom: 12rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
}

.footer {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 20rpx 32rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  
  :deep(.u-button) {
    height: 88rpx;
    border-radius: 44rpx;
    font-size: 32rpx;
    font-weight: 500;
    
    &:active {
      transform: scale(0.98);
    }
  }
}
</style>
